//
//  ReportViewController.m
//  mendianjieke
//
//  Created by 响当当 on 7/30/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "ReportViewController.h"
#import <WebKit/WKWebView.h>
#import <WebKit/WebKit.h>
#import <DWKWebView.h>
#import "JsApiTest.h"

@interface ReportViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property (nonatomic,strong)DWKWebView *webView;
@property (nonatomic, strong)NSMutableArray *arr;
@end

@implementation ReportViewController

- (NSMutableArray *)arr
{
    if (!_arr)
    {
        _arr = [[NSMutableArray alloc]init];
    }
    return _arr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"报告"];
    
    [self configSubView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshWebView:) name:@"REFRESH_WEBVIEW" object:nil];

    
    [self getinfo];
}

#pragma 配置子视图
- (void)configSubView
{
    self.webView = [self getCookieWebview];
    [self.view addSubview:self.webView];
    
}

- (DWKWebView *)getCookieWebview
{
    WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
    // 设置偏好设置
    webConfig.preferences = [[WKPreferences alloc] init];
    // 默认为0
    webConfig.preferences.minimumFontSize = 10;
    // 默认认为YES
    webConfig.preferences.javaScriptEnabled = YES;
    // 在iOS上默认为NO，表示不能自动通过窗口打开
    webConfig.preferences.javaScriptCanOpenWindowsAutomatically = true;
    
    // web内容处理池
    webConfig.processPool = [[WKProcessPool alloc] init];
    // 将所有cookie以document.cookie = 'key=value';形式进行拼接
    NSString *cookieValue = [NSString stringWithFormat:@"document.cookie = 'access_token=%@'; document.cookie = 'device=%@';",current_User.token,@"ios"];
    WKUserContentController* userContentController = WKUserContentController.new;
    WKUserScript * cookieScript = [[WKUserScript alloc]
                                   initWithSource: cookieValue
                                   injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [userContentController addUserScript:cookieScript];
    webConfig.userContentController = userContentController;
    
    _webView = [[DWKWebView alloc]initWithFrame:CGRectMake(0,NAVIBAR_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT-NAVIBAR_HEIGHT-TABBAR_HEIGHT) configuration:webConfig];
    _webView.navigationDelegate = self;
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/ec/report",WEBCOMME_HOST]]];
    [_webView loadRequest:request];
    
    [_webView addJavascriptObject:[[JsApiTest alloc]init] namespace:nil];
    
    return _webView;
}

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    
}

// 1. 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL *url = navigationAction.request.URL;
    NSString *scheme = [url scheme];
    if ([scheme isEqualToString:@"tel"] || [scheme isEqualToString:@"weixin"])
    {
        [[UIApplication sharedApplication] openURL:url];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
// 4, 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
    decisionHandler(WKNavigationResponsePolicyAllow);
    
}
// 8页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    
}

- (void)getinfo
{
//    dispatch_group_t group = dispatch_group_create();
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//
    NSMutableArray *arr = [[NSMutableArray alloc]init];
//
//    dispatch_group_async(group,queue, ^{
//
//        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
//
//        [infoManager recordLineChart:[NSDictionary new]
//                              sucess:^(id  _Nonnull acceptData) {
//
//                                  [arr addObject:acceptData];
//                                  dispatch_semaphore_signal(sema);
//
//                              }
//                                fail:^(NSError * _Nullable error) {
//
//                                }];
//
//        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
//    });
//
//    dispatch_group_async(group,queue, ^{
//        NSDictionary *pramaters = @{
//                                    @"date" : [Utilties getYearAndMonth],
//                                    };
//
//        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
//
//        [infoManager recordStatistics:pramaters
//                               sucess:^(id  _Nonnull acceptData) {
//
//                                   [arr addObject:acceptData];
//                                   dispatch_semaphore_signal(sema);
//                               }
//                                 fail:^(NSError * _Nullable error) {
//
//                                 }];
//        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
//    });
//
//
//    dispatch_group_async(group,queue, ^{
//
//        NSDictionary *pramaters = @{
//                                    @"date" : [Utilties getYearAndMonth],
//                                    @"type" : @"0"
//                                    };
//
//        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
//
//        [infoManager recordList:pramaters
//                         sucess:^(id  _Nonnull acceptData) {
//
//                             [arr addObject:acceptData];
//                             dispatch_semaphore_signal(sema);
//                         }
//                           fail:^(NSError * _Nullable error) {
//
//                           }];
//        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
//    });
//
//    dispatch_group_notify(group,dispatch_get_main_queue(), ^{
//
//        NSDictionary *dic = arr[0];
//        NSString *str = [Utilties convertJSONWithDic:dic];
//        NSLog(@"%@",str);
//
//        NSDictionary *dics = arr[1];
//        NSString *strs = [Utilties convertJSONWithDic:dics];
//        NSLog(@"%@",strs);
//
//        NSString *strss = [Utilties convertJSONWithDic:arr[2]];
//        NSArray *infoarr = [[NSArray alloc]initWithObjects:str,strs,strss, nil];
////
//        [self.webView callHandler:@"allDataIOS" arguments:infoarr completionHandler:^(id  _Nullable value) {
//
//        }];
//    });
    
    
    [infoManager recordLineChart:[NSDictionary new]
                          sucess:^(id  _Nonnull acceptData) {
                              
                              [arr addObject:acceptData];
                              
                              NSDictionary *pramaters = @{
                                                          @"date" : [Utilties getYearAndMonth],
                                                          };
                              
                              [infoManager recordStatistics:pramaters
                                                     sucess:^(id  _Nonnull acceptData) {
                                                         
                                                         [arr addObject:acceptData];
                                                         
                                                         NSDictionary *pramaters = @{
                                                                                     @"date" : [Utilties getYearAndMonth],
                                                                                     @"type" : @"0"
                                                                                     };
                                                         
                                                         [infoManager recordList:pramaters
                                                                          sucess:^(id  _Nonnull acceptData) {
                                                                              
                                                                              [arr addObject:acceptData];
                                                                             
                                                                              NSDictionary *dic = arr[0];
                                                                              NSString *str = [Utilties convertJSONWithDic:dic];
                                                                              
                                                                              NSDictionary *dics = arr[1];
                                                                              NSString *strs = [Utilties convertJSONWithDic:dics];
                                                                              
                                                                              NSString *strss = [Utilties convertJSONWithDic:arr[2]];
                                                                              NSArray *infoarr = [[NSArray alloc]initWithObjects:str,strs,strss, nil];
                                                                              
                                                                              [self.webView callHandler:@"allDataIOS" arguments:infoarr completionHandler:^(id  _Nullable value) {
                                                                                  
                                                                              }];
                                                                          }
                                                                            fail:^(NSError * _Nullable error) {
                                                                                
                                                                            }];
                                                     }
                                                       fail:^(NSError * _Nullable error) {
                                                           
                                                       }];
                              
                          }
                            fail:^(NSError * _Nullable error) {
                                
                            }];

}

- (void)refreshWebView: (NSNotification *) notification
{
    NSDictionary *dic = notification.object;
    
    NSMutableArray *arr = [[NSMutableArray alloc]init];

    [infoManager recordLineChart:[NSDictionary new]
                          sucess:^(id  _Nonnull acceptData) {
                              
                              [arr addObject:acceptData];
                              
                              NSDictionary *pramaters = @{
                                                          @"date" : dic[@"date"],
                                                          };
                              
                              [infoManager recordStatistics:pramaters
                                                     sucess:^(id  _Nonnull acceptData) {
                                                         
                                                         [arr addObject:acceptData];
                                                         
                                                         NSDictionary *pramaters = @{
                                                                                     @"date" : dic[@"date"],
                                                                                     @"type" : dic[@"type"]
                                                                                     };
                                                         
                                                         [infoManager recordList:pramaters
                                                                          sucess:^(id  _Nonnull acceptData) {
                                                                              
                                                                              [arr addObject:acceptData];
                                                                              
                                                                              NSDictionary *dic = arr[0];
                                                                              NSString *str = [Utilties convertJSONWithDic:dic];
                                                                              
                                                                              NSDictionary *dics = arr[1];
                                                                              NSString *strs = [Utilties convertJSONWithDic:dics];
                                                                              
                                                                              NSString *strss = [Utilties convertJSONWithDic:arr[2]];
                                                                              NSArray *infoarr = [[NSArray alloc]initWithObjects:str,strs,strss, nil];
                                                                              
                                                                              [self.webView callHandler:@"allDataIOS" arguments:infoarr completionHandler:^(id  _Nullable value) {
//                                                                                  [[NSNotificationCenter defaultCenter] removeObserver:self name:@"REFRESH_WEBVIEW" object:nil];
                                                                              }];
                                                                          }
                                                                            fail:^(NSError * _Nullable error) {
                                                                                
                                                                            }];
                                                     }
                                                       fail:^(NSError * _Nullable error) {
                                                           
                                                       }];
                              
                          }
                            fail:^(NSError * _Nullable error) {
                                
                            }];

}

@end
